#include <string.h>
#include <malloc.h>
#include "rsrclist.h"
#include "../global.h"
#include "../log/log.h"



CLNode_s* RL_list = NULL;


void RL_init(void)
{
  RL_list = CL_create();
  if( RL_list == NULL )
  {
    LOG_add(LOG_FATAL, "RSRCLIST cannot create the list.");
  }
}

void RL_destroy(void)
{
  CL_map(RL_list, free);
  CL_destroy(RL_list);
}


void RL_add(resource_s* rsrc)
{
  CLNode_s* node;
  resource_s* new_rsrc;

  node = CL_search_user(RL_list, (char(*)(void*,void*))RL_test, rsrc);
  if( node == NULL )
  {
    new_rsrc = (resource_s*)malloc( sizeof(*new_rsrc) );
    if( new_rsrc == NULL )
    {
      LOG_add(LOG_FATAL, "RSRCLIST malloc failed.");
      return;
    }
    memcpy(new_rsrc, rsrc, sizeof(*new_rsrc));

    if( CL_push(RL_list, new_rsrc) == NULL )
    {
      LOG_add(LOG_FATAL, "RSRCLIST cannot add a resource.");
      return;
    }
  }
  else if( rsrc->local && !((resource_s*)node->data)->local )
  {
    *((resource_s*)node->data) = *rsrc;
  }
}


void RL_remove(resource_s* rsrc)
{
  CLNode_s* node;

  node = CL_search_user(RL_list, (char(*)(void*,void*))RL_test, rsrc);
  if( node != NULL )
  {
    free(node->data);
    CL_remove(node);
  }
  else
  {
    LOG_add(LOG_WARNING, "RSRCLIST resource not found for removal.");
  }
}


inline char RL_test(resource_s* rsrc1, resource_s* rsrc2)
{
  return ( memcmp(rsrc1->key, rsrc2->key, sizeof(filekey_t)) == 0 ) ? 1 : 0;
}

